package com.johnson.news.adapter;

import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

public class CommonViewPagerAdapter extends PagerAdapter {
    private int mChildCount = 0;
    public CommonViewPagerAdapter(){

    }

    boolean isLoopEnabled = false;
    public void setLoopEnabled(boolean enabled){
        isLoopEnabled = enabled;
    }

    ArrayList<String> titleList = new ArrayList<>();
    public void setTitleList(ArrayList<String> list){
        titleList.clear();
        titleList.addAll(list);
    }

    ArrayList<View> viewList = new ArrayList<>();
    public void setViews(ArrayList<? extends View> list){
        viewList.clear();
        viewList.addAll(list);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        if(isLoopEnabled)
            return viewList.size() > 0 ? viewList.size() * 300 : 0;
        else
            return viewList.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        int realPos = (position > 0 && position >= viewList.size()) ? (position % viewList.size()) : position;
        if(viewList.get(realPos).getParent() != null)
            ((ViewGroup) viewList.get(realPos).getParent()).removeView(viewList.get(realPos));
        if(viewList.get(realPos).getParent() == null)
            container.addView(viewList.get(realPos));
        return viewList.get(realPos);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        int realPos = position >= viewList.size() ? (position % viewList.size()) : position;
        container.removeView(viewList.get(realPos));
    }

    @Override
    public CharSequence getPageTitle(int position) {
        if(titleList.size() > 0) {
            if(titleList.size() >= position)
                return titleList.get(position % titleList.size());
            else
                return titleList.get(position);
        } else
            return "";
    }


    @Override
    public void notifyDataSetChanged() {
        mChildCount = getCount();
        super.notifyDataSetChanged();
    }

    @Override
    public int getItemPosition(Object object)   {
        if (mChildCount > 0) {
            mChildCount --;
            return POSITION_NONE;
        }
        return super.getItemPosition(object);
    }
}
